package upm.pb4agent.team5.common;

import jade.content.Concept;
import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import upm.pb4agent.ontology.PickSeat;
import upm.pb4agent.ontology.RealRow;

public class BBoatManageMessages extends CyclicBehaviour {
	private static final long serialVersionUID = 4725497336153171173L;

	private Boat boat = null;

	public BBoatManageMessages(Boat boat) {
		this.boat = boat;
	}
	
	public void action() {
		ACLMessage msg = boat.blockingReceive(getTemplate());
		Concept concept;
		try {
			concept = boat.getConcept(msg);

			if (concept instanceof PickSeat) {
				PickSeat pickSeat = (PickSeat) concept;
				AID rowerAID = msg.getSender();
				
				pickSeat(pickSeat, rowerAID);
			} else if (concept instanceof RealRow) {
				RealRow realRow = (RealRow) concept;
				
				boat.toRow (realRow.getX(), realRow.getY());
			}

		} catch (Exception e) {
			System.err.println(boat.getLocalName() + ": Error managing message");
		}
		
	}
	
	private void pickSeat(PickSeat pickSeat, AID rowerAID) throws CodecException, OntologyException {
		boat.addRower(rowerAID.getLocalName(), pickSeat.getSeatID().getSeatID());
		
		// TODO: Validate pick seat, see: boat.getRowers().get(seatID);
		boat.send(pickSeat, rowerAID, ACLMessage.INFORM);
		System.out.println(boat.getLocalName() + ": SeatID " + pickSeat.getSeatID().getSeatID() + 
				" assigned to " + rowerAID.getLocalName());
	}
	
	private MessageTemplate getTemplate() {
		MessageTemplate template = MessageTemplate.or(
				MessageTemplate.MatchProtocol(PickSeat.class.getSimpleName()), 
				MessageTemplate.MatchProtocol(RealRow.class.getSimpleName())
			);
		
		return template; 		
	}
}
